<script setup lang="ts">
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { computed, reactive, ref, watch } from 'vue';
import { useForm } from '@sa/alova/client';
import { useNaiveForm } from '@/hooks/common/form';
import { fetchRolePermission, updateRolePermission } from '@/service/api/manage';

defineOptions({
  name: 'PermissionDrawer'
});

interface Props {
  rowData?: Api.Row | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});
const { formRef } = useNaiveForm();

const {
  loading: submitting,
  reset,
  send: submit,
  form: model,
  updateForm
} = useForm(formData => updateRolePermission(formData), {
  initialForm: {
    roleId: 0,
    roleName: '',
    permissionIdList: []
  } as Api.Manage.RolePermission,
  resetAfterSubmiting: true
});

async function handleInitModel() {
  if (props.rowData?.id) {
    const roleId = Number(props.rowData.id);
    const data = await fetchRolePermission(roleId);
    model.value = data;
    updateForm(model.value);
  } else {
    reset();
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  // request
  await submit();

  window.$message?.success('更新成功');
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
  } else {
    reset();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent title="角色权限" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model">
        <NFormItem label="角色" path="roleName">
          <NInput v-model:value="model.roleName" placeholder="角色" disabled />
        </NFormItem>
        <NFormItem label="权限" path="permissionIdList">
          <PorTree
            :checked-keys="model.permissionIdList || []"
            url="/permission/getMenuTree"
            multiple
            @update:checked-keys="(keys: number[]) => (model.permissionIdList = keys)"
          ></PorTree>
        </NFormItem>
      </NForm>
      <template #footer>
        <NGrid :x-gap="6" :cols="2" layout-shift-disabled>
          <NGi>
            <NSpace :size="16" justify="start">
              <NButton type="error" class="drawer-footer-left">清空权限</NButton>
            </NSpace>
          </NGi>
          <NGi>
            <NSpace :size="16" justify="end">
              <NButton @click="closeDrawer">取消</NButton>
              <NButton type="primary" :loading="submitting" @click="handleSubmit">确认</NButton>
            </NSpace>
          </NGi>
        </NGrid>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
